package com.ssoclient.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ssoclient.utils.CommonCode;
import com.ssoclient.utils.HttpClient;
import com.ssoclient.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 11900
 * @version V1.0
 * @Title: ${FILE_NAME}
 * @Package com.ssoclient.filter
 * @Description: TODO
 * @date 2020/4/27 13:05
 */
@Component
@WebFilter(urlPatterns = "/**", filterName = "loginFilter")
public class LoginFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${sso_server}")
    private String serverHost;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        if (httpServletRequest.getRequestURI().startsWith("/static")) {

            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token =  httpServletRequest.getHeader("Authorization");
        if (this.check(token)) {

            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(JSON.toJSONString(ResultUtil.build(CommonCode.LOGNOT)));
        }
    }

    private boolean check(String token) {
        try {
            if (StrUtil.isEmpty(token)) {
                return false;
            }
            JSONObject object = HttpClient.get(serverHost + "/checkJwt",token);
            return object.getBoolean("flag");
        } catch (Exception e) {
            logger.error("向认证中心请求失败", e);
            return false;
        }

    }
}